package com.example.dp.jiemian.bt1.bean;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.CornerPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.dp.jiemian.R;

import java.util.List;

/**
 * Created by DP on 2018/4/10.
 */

public class ViewPagerIndicator extends LinearLayout {

    private Paint mPaint;
    private Path mPath;
    private int mTriangleHeigh;//三角形高
    private int mTriangleWidth;

    private static final float RADIO_TRIANGLE_WIDTH = 1 / 6F;//三角形的底部为每个模块的6分之一
    private final int DIMENSION_TRIANGLE_WINTH_MAX = (int)(getScreenWidth()/3 *RADIO_TRIANGLE_WIDTH);//三角形底边最大的宽度

    private int mInitTranslationX;//偏移位置，初始位置
    private int mTranslationX;//移动的位置
    private int mTabVisibleCount;//自定义数量tab
    private static final int COUNT_DEFAULT_TAB = 4;

    private static final int COLOR_TEXT_MIN = 0xFF7A7A7A;
    private static final int COLOR_TEXT_MAN = 0xFF000000;

    private ViewPager mViewPager;

    private List<String> mTitles;


    public ViewPagerIndicator(Context context) {
        this(context, null);
    }

    public ViewPagerIndicator(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        //获取可见Tab的数量
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ViewPagerIndicator);
        mTabVisibleCount = a.getInt(R.styleable.ViewPagerIndicator_visible_tab_count, COUNT_DEFAULT_TAB);
        if (mTabVisibleCount < 0) {
            mTabVisibleCount = COUNT_DEFAULT_TAB;
        }
        a.recycle();

        //初始化画笔
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.WHITE);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setPathEffect(new CornerPathEffect(3));
    }

    @Override//获取tab数量，并设置宽度
    protected void onFinishInflate() {
        super.onFinishInflate();

        int cCount = getChildCount();
        if (cCount == 0) return;
        for (int i = 0; i < cCount; i++) {
            View view = getChildAt(i);
            LinearLayout.LayoutParams lp = (LayoutParams) view.getLayoutParams();
            lp.weight = 0;
            lp.width = getScreenWidth() / mTabVisibleCount;
            view.setLayoutParams(lp);
        }
        setItemClickEvent();
    }

    @Override//初始三角形位置
    protected void dispatchDraw(Canvas canvas) {
        canvas.save();
        canvas.translate(mInitTranslationX + mTranslationX, getHeight() + 2);
        canvas.drawPath(mPath, mPaint);

        canvas.restore();

        super.dispatchDraw(canvas);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        mTriangleWidth = (int) (w / mTabVisibleCount * RADIO_TRIANGLE_WIDTH);
        mTriangleWidth = Math.min(mTriangleWidth,DIMENSION_TRIANGLE_WINTH_MAX);
        mInitTranslationX = w / mTabVisibleCount / 2 - mTriangleWidth / 2;
        initTriangle();
    }

    //初始化三角形
    private void initTriangle() {

        mTriangleHeigh = mTriangleWidth / 2;

        mPath = new Path();
        mPath.moveTo(0, 0);
        mPath.lineTo(mTriangleWidth, 0);
        mPath.lineTo(mTriangleWidth / 2, -mTriangleHeigh);
        mPath.close();
    }

    //指示器跟随手机进行滚动
    public void scroll(int position, float positionOffset) {
        int tabWidth = getWidth() / mTabVisibleCount;
        mTranslationX = (int) (tabWidth * (positionOffset + position));

        //容器移动，当tab处于移动至最后一个时
        if (position>=mTabVisibleCount-2&&position<getChildCount()-2&&positionOffset>0&&getChildCount()>mTabVisibleCount) {
            if (mTabVisibleCount != 1) {
                this.scrollTo((position - (mTabVisibleCount - 2)) * tabWidth + (int) (tabWidth * positionOffset), 0);
            } else {
                this.scrollTo(position * tabWidth + (int) (tabWidth + positionOffset), 0);
            }
        }

        invalidate();//滚动后实时更新
    }

    //获得屏幕宽度
    public int getScreenWidth() {
        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    public void setTabItemTitles(List<String> titles){
        if (titles != null && titles.size()>0){
            this.removeAllViews();
            mTitles = titles;
            for (String title:mTitles){
                addView(generateTextView(title));
            }
            setItemClickEvent();
        }
    }

    //设置可见的tab数量
    public void setVisibleTabCount(int count){
        mTabVisibleCount = count;
    }

    //根据tiele创建Tab
    private View generateTextView(String title) {
        TextView textView = new TextView(getContext());
        LinearLayout.LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
        lp.width = getScreenWidth()/mTabVisibleCount;
        textView.setText(title);
        textView.setGravity(Gravity.CENTER);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
        textView.setTextColor(COLOR_TEXT_MIN);
        textView.setLayoutParams(lp);
        return textView;
    }


    public interface PageOnchangeListener{
        void onPageScrolled(int position, float positionOffset, int positionOffsetPixels);

        void onPageSelected(int position);

        void onPageScrollStateChanged(int state);
    }

    public PageOnchangeListener mListener;

    public void setOnPageChangeListener(PageOnchangeListener listener){
        this.mListener = listener;
    }

    //设置关联的ViewPager
    public void setViewPager(ViewPager viewPager,int pos) {
        mViewPager = viewPager;
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                //tabWidth * positionOffset + position * tabwidth
                //把偏移量传入管理
                scroll(position, positionOffset);
                if (mListener != null) {
                    mListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
                }
            }

            @Override
            public void onPageSelected(int position) {
                if (mListener != null) {
                    mListener.onPageSelected(position);
                }
                highLightTextView(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (mListener != null) {
                    mListener.onPageScrollStateChanged(state);
                }
            }
        });
        mViewPager.setCurrentItem(pos);
        highLightTextView(pos);
    }

    //重置Tab文本颜色
    private void resetTextViewColor(){
        for (int i = 0;i<getChildCount();i++){
            View view = getChildAt(i);
            if (view instanceof TextView){
                ((TextView) view).setTextColor(COLOR_TEXT_MIN);
            }
        }
    }

    //高亮某个tab的文本
    private void highLightTextView(int pos){
        resetTextViewColor();
        View view = getChildAt(pos);
        if (view instanceof TextView){
            ((TextView) view).setTextColor(COLOR_TEXT_MAN);
        }
    }

    //设置tab的点击事件
    private void setItemClickEvent(){
        int cCount = getChildCount();
        for (int i =0;i<cCount;i++){
            final int j = i;
            View view = getChildAt(i);
            view.setOnClickListener(v -> {
                mViewPager.setCurrentItem(j);
            });
        }
    }
}
